package cn.wp.order.service.impl;

import cn.wp.basic.constant.BusinessConstant;
import cn.wp.basic.domain.Point;
import cn.wp.basic.service.impl.BaseServiceImpl;
import cn.wp.basic.util.CodeGenerateUtils;
import cn.wp.basic.util.DistanceUtil;
import cn.wp.order.domain.OrderAddress;
import cn.wp.order.domain.ProductOrder;
import cn.wp.order.domain.ProductOrderDetail;
import cn.wp.order.mapper.OrderAddressMapper;
import cn.wp.order.mapper.ProductOrderDetailMapper;
import cn.wp.order.mapper.ProductOrderMapper;
import cn.wp.order.service.IProductOrderService;
import cn.wp.org.domain.Shop;
import cn.wp.org.mapper.ShopMapper;
import cn.wp.pay.domain.AlipayInfo;
import cn.wp.pay.domain.PayBill;
import cn.wp.pay.mapper.AlipayInfoMapper;
import cn.wp.pay.mapper.PayBillMapper;
import cn.wp.pay.service.IPayBillService;
import cn.wp.product.domain.Product;
import cn.wp.product.mapper.ProductMapper;
import cn.wp.quartz.config.MainJob;
import cn.wp.quartz.domain.QuartzInfo;
import cn.wp.quartz.service.IQuartzInfoService;
import cn.wp.user.domain.User;
import cn.wp.user.domain.UserAddress;
import cn.wp.user.mapper.UserAddressMapper;
import cn.wp.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IQuartzInfoService quartzInfoService;

    @Override
    @Transactional
    public String createOrder(Map<String, String> params, User user) {
        /*
            要操作的表
            t_order_product
            t_order_product_detail
            t_order_address
        */
        /*  前台传的值
            addressId	1
            payId	"aliPay"
            productId	8
        */
        // 获取前台传过来的商品id，转换为Long类型
        Long id = Long.valueOf(params.get("productId"));
        // 根据id查询对应的商品
        Product product = productMapper.loadOne(id);
        // 根据登录用户的id，查询出对应的地址
        UserAddress userAddress = userAddressMapper.loadOne(user.getId());

        // 操作ProductOrder表，生成服务订单
        ProductOrder productOrder = createProductOrder(product,user,userAddress);
        productOrderMapper.save(productOrder);

        // 操作t_order_product_detail表，生成服务订单详情
        ProductOrderDetail productOrderDetail = createProductOrderDetail(product);
        // 设置服务订单id
        productOrderDetail.setOrder_id(productOrder.getId());
        productOrderDetailMapper.save(productOrderDetail);

        // 操作t_order_address表,生成服务订单地址
        OrderAddress orderAddress = createOrderAddress(userAddress);
        // 设置服务订单id
        orderAddress.setOrder_id(productOrder.getId());
        // 设置订单号
        orderAddress.setOrderSn(productOrder.getOrderSn());
        // 保存数据
        orderAddressMapper.save(orderAddress);

        // 操作t_pay_bill，生成支付单
        PayBill payBill = createPayBill(productOrder);
        payBillMapper.save(payBill);

        // 添加定时任务
        QuartzInfo quartzInfo = new QuartzInfo();
        // 名称
        quartzInfo.setJobName("product" + productOrder.getOrderSn());
        // 任务类，关键业务逻辑
        quartzInfo.setCls(MainJob.class);
        // 最后支付的时间
        quartzInfo.setTime(productOrder.getLastPayTime());
        // 定时任务的参数
        Map<String, Object> map = new HashMap<>();
        map.put("orderSn", productOrder.getOrderSn());
        quartzInfo.setParams(map);
        quartzInfoService.addJob(quartzInfo);

        AlipayInfo alipayInfo = alipayInfoMapper.loadByShodId(payBill.getShop_id());
        System.out.println(alipayInfo.getAppid());
        // 提交支付数据
        String result = payBillService.paySubmit(payBill, alipayInfo);
        return result;
    }

    /**
     * 生成支付单
     * @param productOrder
     * @return
     */
    private PayBill createPayBill(ProductOrder productOrder){
        PayBill payBill = new PayBill();
        // 摘要
        payBill.setDigest(productOrder.getDigest());
        // 价格
        payBill.setMoney(productOrder.getPrice());
        // 状态 0 默认未支付
        payBill.setState(0);
        // 支付方式
        payBill.setPayChannel(1L);

        // 创建时间
        payBill.setCreateTime(new Date());
        // 用户id
        payBill.setUser_id(productOrder.getUser_id());
        // 店铺id
        payBill.setShop_id(productOrder.getShop_id());
        // 订单码
        payBill.setOrderSn(productOrder.getOrderSn());
        // businessType 业务类型
        payBill.setBusinessType(BusinessConstant.PRODUCT_ORDER);
        // businessKey  业务主键
        payBill.setBusinessKey(productOrder.getId());
        return payBill;
    }

    /**
     * 生成服务订单地址
     * @param userAddress
     * @return
     */
    private OrderAddress createOrderAddress(UserAddress userAddress){
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        return orderAddress;
    }

    /**
     * 生成服务订单详情
     * @param product
     * @return
     */
    private ProductOrderDetail createProductOrderDetail(Product product){
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,productOrderDetail );
        // 设置商品id
        productOrderDetail.setProduct_id(product.getId());
        return productOrderDetail;
    }

    /**
     * 生成服务订单
     * @param product
     * @param user
     * @param userAddress
     * @return
     */
    private ProductOrder createProductOrder(Product product,User user,UserAddress userAddress){
        ProductOrder productOrder = new ProductOrder();
        // 设置摘要
        productOrder.setDigest("[服务订单]"+product.getName());
        // 设置状态
        productOrder.setState(0);
        // 设置商品价格
        productOrder.setPrice(product.getSaleprice());
        // 设置订单号
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        // 设置最后支付时间 半小时
        Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 3);
        productOrder.setLastPayTime(date);
        // 设置商品id
        productOrder.setProduct_id(product.getId());
        // 设置用户id
        productOrder.setUser_id(user.getId());
        // 通过userAddress用户地址查询出详细地址，
        Point point1 = DistanceUtil.getPoint(userAddress.getFullAddress());
        // 查询所有门店
        List<Shop> shops = shopMapper.loadAll();
        // 计算最近的门店
        Shop shop = DistanceUtil.getNearestShop(point1, shops);
        // 设置最近的门店id
        productOrder.setShop_id(shop.getId());
        return productOrder;
    }
}
